<style scoped>
.clientSales {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.clientSales_top {
  display: flex;
  padding: 1.5vh 0;
  white-space: nowrap;
}
.t_content {
  margin: 0 8px 0 12px;
  padding-top: 3px;
}
.clientSales input:focus {
  outline: none;
  border: 1px solid #017aff;
}
.inp {
  border: 1px solid #dbdbdb;
  border-radius: 3px;
  height: 30px;
  padding: 0 5px;
}
.inp2 {
  width: 8vw;
}
.inp3 {
  width: 3vw;
  margin-right: 0.5vw;
}
.inp4 {
  width: 90px;
  margin-left: -1px;
}
.inp5 {
  width: 8vw;
}
.inp6 {
  width: 3.5vw;
  margin-right: 0.5vw;
}
.a_color {
  color: #017aff;
}
.clientSales_c {
  display: flex;
  width: 100%;
  height: 87%;
  border-top: 2px solid #f4f4f4;
}
/*                   566464646*/
.content1 {
  width: 30%;
  border-right: 2px solid #f4f4f4;
  padding-right: 0.5vw;
  height: 87vh;
}
.content2 {
  width: 70%;
  /* height: 100%; */
  padding-left: 10px;
}
.c_button {
  width: 35px;
  height: 30px;
  margin: 0 0 0 -1px;
  /* padding:4px 6px 0 0; */
  background: #dbdbdb;
  font-size: 13px;
  border: 0px solid #dbdbdb;
  outline: none;
}
.hand {
  cursor: pointer;
}
.c2 {
  display: flex;
  margin: 1vh 0;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.c2_2 {
  display: flex;
}
.c2_1 {
  display: flex;
}
.c2_2 p {
  margin-right: 0.5vw;
}
.check {
  width: 90px;
  border: 1px solid #d3cdcd;
  border-radius: 5px;
  padding: 8px 0 0 7px;
}
.c2_button {
  height: 25px;
  margin: 8px 5px 0 35px;
}
.c2_button1 {
  height: 25px;
  margin: 8px 5px 0 0;
}
.content2_1 {
  margin-top: 3px;
}
.date_1 {
  margin: 3px 6px 0 0;
}
.remarks_1 {
  margin: 3px 6px 0 32px;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
.print {
  width: 264px;
  height: 120px;
  background: white;
  position: absolute;
  top: 26%;
  left: 37%;
  z-index: 2;
  padding: 10px 15px;
  box-shadow: 3px 3px 3px #f4f4f4;
}
.print div:first-child {
  font-weight: 700;
  margin-bottom: 5px;
}
.print div:last-child {
  float: right;
  margin: 10px 0 0 0;
}
</style>

<style>
.clientSales .el-input__icon {
  line-height: 30px;
}
.clientSales .el-input__inner,
.clientSales .el-input {
  height: 30px;
}
.clientSales .clientSales_top .sty .el-input__inner {
  height: 30px;
  width: 4.5vw;
}
.clientSales .clientSales_top .sty .el-checkbox.is-bordered {
  padding: 4px 6px 0px 5px;
  height: 30px;
}
.clientSales .clientSales_top .ph .el-input__inner {
  height: 30px;
  width: 8vw;
}
.clientSales .el-date-editor {
  width: 8vw;
}
.clientSales .c_b .el-button {
  padding: 0;
}
.clientSales .c2_2 .check {
  margin: 0 16px 0 0;
  width: 70px;
  height: 30px;
  padding: 3px 0 0 7px;
}

.clientSales .c2_2 .el-button {
  width: 40px;
}
.clientSales .c2 .el-button {
  margin: 0 10px 0 0 !important;
}
.clientSales .print .el-radio {
  margin-right: 19px;
}
.clientSales .el-table__footer td {
  height: 26px;
}
.clientSales .el-table .cell {
  padding: 0 0 0 5px;
}
</style>

<template>
  <div class="clientSales">
    <div class="clientSales_top">
      <p class="t_content">销货日期</p>
      <div class="ph">
        <el-date-picker
          v-model="inputDate"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期"
          :disabled="Boolean(switchList.length)"
        >
        </el-date-picker>
      </div>

      <p class="t_content">客户编号</p>
      <!-- <input class="inp inp3" type="text" v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"> -->
      <div>
        <el-select
          style="width: 8vw"
          filterable
          v-model="customerName"
          @change="
            (e) => {
              this.customerNo = e
            }
          "
          :disabled="jxAgent"
        >
          <el-option
            v-for="item in customerList"
            :key="item.value"
            :label="item.value + '  ' + item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>

      <p class="t_content">单号</p>
      <input class="inp inp2" type="text" v-model="inputSequence" disabled />

      <p class="t_content">客销序号</p>
      <input class="inp inp2" type="text" v-model="sequence" />

      <p class="t_content">折数</p>
      <input
        class="inp inp6"
        type="text"
        v-model="discount"
        :disabled="!checked1"
      />
      <div class="sty">
        <el-checkbox v-model="checked1" label="改动" border></el-checkbox>
      </div>

      <p class="t_content">配货方式</p>
      <div class="sty">
        <el-select v-model="cooperateWay">
          <el-option
            v-for="item in cooperateWayList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-checkbox
          style="margin-left: 10px"
          v-model="checked2"
          label="返现"
          border
        ></el-checkbox>
      </div>

      <p class="t_content">备注</p>
      <input class="inp inp5" type="text" v-model="remark" />

      <p class="t_content a_color hand">修改</p>
    </div>

    <div class="clientSales_c">
      <div class="content1">
        <div style="margin-top: 1vh">
          <el-table
            :data="kindsNumberList"
            style="width: 100%"
            height="86vh"
            highlight-current-row
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
          >
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="kindsNumber" label="货号" width="200">
            </el-table-column>
            <el-table-column prop="sellingPrice" label="售价">
            </el-table-column>
            <el-table-column prop="sum" label="数量"> </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="content2">
        <div class="c2">
          <div class="c2_1">
            <el-button @click="create" type="primary" icon="el-icon-plus"
              >新建</el-button
            >
            <el-button
              @click="confirm"
              icon="el-icon-circle-check"
              :disabled="isConfirm"
              >确认</el-button
            >
            <el-button @click="exportExcel" icon="el-icon-upload2"
              >导出</el-button
            >
            <!-- <div class="dr">
              <i class="el-icon-download"></i>
              导入
              <input
                @change="readExcel"
                accept=".xls, .xlsx"
                class="outputlist_upload"
                type="file"
                ref="upload"
              />
            </div> -->
            <el-button size="small" class="a-upload el-icon-download"
              >导入
              <template>
                <input
                  type="file"
                  accept=".xlsx,.xls"
                  @change="handleImportInputClick"
                  class="file"
                  id="file"
                />
              </template>
            </el-button>
            <el-button @click="printConfirm" icon="el-icon-printer"
              >列印</el-button
            >
            <el-button @click="dele" icon="el-icon-delete" :disabled="isConfirm"
              >删除</el-button
            >
          </div>

          <div class="c2_2">
            <p>合计：{{ total }}</p>
            <p>销货序号：{{ sequence }}</p>
            <el-checkbox class="check" v-model="twoDimensional"
              >二维</el-checkbox
            >
            <!-- <el-button icon="el-icon-arrow-left"></el-button>
            <el-button icon="el-icon-arrow-right"></el-button> -->
          </div>
        </div>

        <div class="content2_1">
          <el-table
            id="outTable"
            :data="switchList"
            style="width: 100%"
            height="82vh"
            ref="table"
            border
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            :header-cell-style="{
              background: '#f4f4f4',
              padding: 0,
              height: '30px'
            }"
            :cell-style="{ padding: 0, height: '26px' }"
          >
            <el-table-column type="index" label="序号" width="50">
            </el-table-column>

            <template v-for="i in knhList">
              <el-table-column
                :prop="i.prop"
                :label="i.label"
                :width="i.width"
                :key="i.prop"
                show-overflow-tooltip
              >
              </el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>

    <!-- <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span>
      </div>
    </foot-view> -->

    <new-build
      :Str="this.Str"
      :style="{ display: showNew_build }"
      :sendData="sendData"
      :flag="showNew_build"
      @closeNew="
        () => {
          ;(this.showNew_build = 'none'), (this.inputDate = this.getNowTime1())
        }
      "
      @saveNew="saveNew"
      @inpNumChange="
        () => {
          this.inpList = this.getInput()
        }
      "
    >
    </new-build>

    <print-area
      v-show="false"
      isInput="销"
      isVendor="客户"
      :manufacturerName="printVendorName"
      :principal="contact"
      :phone="phone"
      :address="address"
      :remark="remark"
      :inputSequence="sequence"
      :jxQuarter="jxQuarter"
      :inputDate="printDate"
      :printTotal="printTotal"
      :printMoney="printMoney"
      :printStyle="printStyle"
      :printSellingPrice="printSellingPrice"
      :printType="printType"
      :shipType="cooperateWay"
      :cellphone="cellphone"
      :companyName="companyName"
      :companyPhone="companyPhone"
    ></print-area>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS')

import { getClient } from '../../../network/client'
import {
  affirmSell,
  getSellInquire,
  sellByKindsNumberContinue,
  sellByKindsNumberSave,
  importCustomerSell
} from '../../../network/sellTotal'
import { getSystemConfig } from '../../../network/operatoryCommand'

import footView from '../../../components/FootView'
import newBuild from './childComp/New_Build'

import XLSX from 'xlsx'
import FileSaver from 'file-saver'

import { importExcel } from '@/util/dealWithExcel'

import enterUp from '../../../components/mixins/enterUp'
import today from '../../../components/mixins/today'
import printArea from '../../../components/PrintVendorStock'
import cookieFn from '../../../components/mixins/cookieFn'

export default {
  name: 'client_sales_mn',
  mixins: [enterUp, today, cookieFn],
  created() {
    this.inpList = this.getInput()
    // 随机数赋值
    this.pageSession = Math.ceil(Math.random() * 1000000) + ''

    this.knhList = this.knhList1

    // 获取所有客户信息
    this.customerList = []
    getClient({ limit: 99999 }).then((res) => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach((e) => {
          if (e.stop != 1) {
            this.customerList.push({ value: e.no, label: e.name })
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              this.customerName = i.value
              break
            }
          }
        }
        this.newSend()
      }
      if (this.$route.query.oid) {
        let min =
          new Date().getMinutes() < 10
            ? '0' + new Date().getMinutes()
            : new Date().getMinutes()
        let sec =
          new Date().getSeconds() < 10
            ? '0' + new Date().getSeconds()
            : new Date().getSeconds()
        console.log(this.strRandom + min + sec) //随机字符串加时间      不重复随机字符串
        this.Str = this.strRandom + min + sec

        this.sequence = this.$route.query.oid
        getSellInquire({
          sellSequence: this.sequence,
          limit: 99999,
          page: 1
        }).then((res) => {
          let list = res.data.data.sellInquireTotalList
          this.customerNo = list[0].no
          this.inputDate = list[0].sellTime + ' 00:00:00'
          this.discount = res.data.data.sellInquireInfoList[0].discount
          this.inputSequence =
            res.data.data.sellInquireInfoList[0].receiptsNumber
          this.cooperateWay = list[0].cooperateWay
          this.remark = list[0].remark
          this.isConfirm = list[0].affirm

          this.customerNoBlur()

          this.showNew_build = 'block'
          this.getData()
          this.newSend()
        })
      }
    })

    getSystemConfig().then((res) => {
      if (res.data.data) {
        this.companyName = res.data.data.companyName
        this.companyPhone = res.data.data.phone
      }
    })
  },
  data() {
    return {
      Str: '',
      strRandom: Math.random().toString(36).substring(2, 7), //随机字符串
      inpList: [],
      sequence: '',
      pageSession: '',
      showNew_build: 'none',

      inputDate: this.getNowTime(),
      customerNo: '',
      customerName: '',
      customerList: [],
      inputSequence: '',
      discount: 10,
      cooperateWay: '配货',
      cooperateWayList: [
        { value: '配货', label: '配货' },
        { value: '订货', label: '订货' },
        { value: '订断', label: '订断' },
        { value: '追断', label: '追断' }
      ],
      remark: '',

      sendData: {},

      checked1: false,
      checked2: false,
      twoDimensional: false,
      printType: '1',

      switchList: [],
      kindsNumberList: [],
      styleNumberList: [],

      knhList: [],
      knhList1: [
        { prop: 'kindsNumber', label: '货号', width: '160' },
        { prop: 'styleNumber', label: '款号', width: '100' },
        { prop: 'colorNo', label: '颜色编号', width: '80' },
        { prop: 'colorName', label: '颜色名称', width: '80' },
        { prop: 'size', label: '尺码', width: '50' },
        { prop: 'sum', label: '数量', width: '80' },
        { prop: 'onePrice', label: '单价', width: '70' },
        { prop: 'money', label: '金额', width: '90' },
        { prop: 'sellingPrice', label: '售价', width: '70' },
        { prop: 'commodityName', label: '品名', width: '160' },
        { prop: 'brandedName', label: '品牌', width: '100' },
        { prop: 'entryTime', label: '录入时间', width: '180' }
      ],
      knhList2: [
        { prop: 'styleNumber', label: '款号', width: '120' },
        { prop: 'colorName', label: '颜色', width: '100' },
        { prop: 'c05', label: '05-XS', width: '100' },
        { prop: 'c07', label: '07-S', width: '100' },
        { prop: 'c09', label: '09-M', width: '100' },
        { prop: 'c11', label: '11-L', width: '100' },
        { prop: 'c13', label: '13-XL', width: '100' },
        { prop: 'c15', label: '15-2L', width: '100' },
        { prop: 'c17', label: '17-3L', width: '100' },
        { prop: 'c19', label: '19-4L', width: '100' },
        { prop: 'c21', label: '21-5L', width: '100' },
        { prop: 'f', label: 'F', width: '80' },
        { prop: 'total', label: '小计', width: '100' },
        { prop: 'sellingPrice', label: '售价', width: '100' },
        { prop: 'money', label: '售价金额', width: '100' },
        { prop: 'brandedName', label: '品牌', width: '110' },
        { prop: 'quarter', label: '季度', width: '100' }
      ],

      operator: this.getCookie('jxUser'),
      jxQuarter: this.getCookie('jxQuarter'),
      jxAgent: this.getCookie('jxAgent') == '1',

      isConfirm: false,

      // 打印
      styleList: [],
      printTotal: 0,
      printMoney: 0,
      // 款号合计
      printStyle: 0,
      // 售价合计
      printSellingPrice: 0,
      // 客户
      printVendor: '',
      printVendorName: '',
      principal: '',
      contact: '',
      phone: '',
      cellphone: '',
      address: '',
      companyName: '',
      companyPhone: '',
      printDate: this.searchDate(),
      total: 0
    }
  },
  watch: {
    twoDimensional(a, b) {
      if (a) {
        this.knhList = this.knhList2
        this.switchList = this.styleNumberList
      } else {
        this.knhList = this.knhList1
        this.switchList = this.kindsNumberList
      }
    },
    inputDate(a, b) {
      this.newNo()
      this.newSend()
    },
    inputSequence(a, b) {
      this.newNo()
      this.newSend()
      if (!a) return
      this.inputSequence = a.toUpperCase().trim()
    },
    sequence(a, b) {
      this.sequence = a.toUpperCase().trim()
      this.newSend()
    },
    discount(a, b) {
      this.newNo()
      this.newSend()
    },
    cooperateWay(a, b) {
      this.newNo()
      this.newSend()
    },
    remark(a, b) {
      this.newNo()
      this.newSend()
    },
    inputDate(a, b) {
      this.newNo()
      if (a) this.printDate = a.slice(0, 10)
    },
    customerNo(a, b) {
      this.newNo()
      this.customerNo = a.toUpperCase().trim()
      this.newSend()
      this.printVendor = a
      getClient({ no: a }).then((res) => {
        this.principal = res.data.data[0].principal || res.data.data[0].name
        this.contact = res.data.data[0].contact || res.data.data[0].name
        this.cellphone = res.data.data[0].phone || ''
        this.phone = res.data.data[0].cellphone || ''
        this.address = res.data.data[0].address || ''
        this.printVendorName = res.data.data[0].no + '_' + res.data.data[0].name
      })
    },
    $route(a, b) {
      this.newSend()
      if (b.path.indexOf('delete_document') != -1) {
        this.newNo()
        return
      }
      if (a.path.indexOf('/customer/client_sales_mn') != -1 && a.query.oid) {
        this.customerList = []
        // 获取所有客户信息
        getClient({ limit: 99999 }).then((res) => {
          if (res.data.code == 200) {
            let list = res.data.data
            list.forEach((e) => {
              if (e.stop != 1) {
                this.customerList.push({ value: e.no, label: e.name })
              }
            })
            this.newSend()
          }
          if (this.$route.query.oid) {
            this.showNew_build = 'block'
            this.sequence = this.$route.query.oid
            getSellInquire({
              sellSequence: this.sequence,
              limit: 99999,
              page: 1
            }).then((res) => {
              let list = res.data.data.sellInquireTotalList
              this.customerNo = list[0].no
              this.inputDate = list[0].sellTime + ' 00:00:00'
              this.discount = res.data.data.sellInquireInfoList[0].discount
              this.inputSequence = list[0].receiptsNumber
              this.cooperateWay = list[0].cooperateWay
              this.remark = list[0].remark

              this.customerNoBlur()

              this.getData()
            })
          }
        })
      }
    }
  },
  components: {
    footView,
    newBuild,
    printArea
  },
  methods: {
    create() {
      this.showNew_build = 'block'
      if (!this.$route.query.oid) {
        if (this.isConfirm) this.isConfirm = false
        this.sequence = ''
        this.switchList = []
        this.kindsNumberList = []
        this.styleNumberList = []
      }
    },

    // 数据变动
    newSend() {
      this.sendData = {
        pageSession: this.pageSession,
        inputDate: this.inputDate,
        customerNo: this.customerNo,
        customerName: this.customerName,
        customerList: this.customerList,
        inputSequence: this.inputSequence,
        sequence: this.sequence,
        discount: this.discount,
        cooperateWay: this.cooperateWay,
        cooperateWayList: this.cooperateWayList,
        remark: this.remark,
        isConfirm: this.isConfirm
      }
    },

    // 确认
    confirm() {
      if (!this.sequence) return
      let d = {
        customerDTO: {
          pageSession: this.pageSession,
          inputDate: this.inputDate,
          customerNo: this.customerNo,
          inputSequence: this.inputSequence,
          sequence: this.sequence,
          warehouseNo: this.warehouseNo,
          discount: this.discount,
          cooperateWay: this.cooperateWay,
          remark: this.remark
        },
        validList: this.kindsNumberList
      }
      affirmSell(JSON.stringify(d)).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '确认成功',
            type: 'success'
          })
          this.isConfirm = true
        } else {
          this.$message.error('确认失败')
        }
      })
    },

    dele() {
      if (!this.sequence) return
      this.$router.push({
        path: '/delete_document',
        query: { type: 5, sequence: this.sequence }
      })
      this.$store.commit('addNav', {
        label: '客户销货删单',
        name: 'delete_document'
      })
    },

    // 导出
    exportExcel() {
      let xlsxParam = { raw: true } //转换成excel时，使用原始的格式
      let wb = XLSX.utils.table_to_book(
        document.querySelector('#outTable'),
        xlsxParam
      )
      let wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream;charset=utf-8' }),
          '客户销货.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    saveNew(res) {
      // console.log(res)
      this.isConfirm = false
      this.readOnly = true

      if (res.sequence) {
        this.inputDate = res.inputDate
        this.customerNo = res.customerNo
        this.customerName = res.customerName
        this.inputSequence = res.inputSequence
        this.discount = res.discount
        this.cooperateWay = res.cooperateWay
        this.remark = res.remark
        this.sequence = res.sequence
        this.getData()
      }
    },

    // 列印
    printConfirm() {
      if (!this.sequence) return
      this.clearPrintTable()
      this.styleList = []
      this.printTotal = 0
      this.printMoney = 0
      this.printStyle = 0
      this.printSellingPrice = 0
      this.openPrint()
    },

    openPrint(x = 1, id = 'printTable') {
      let index = --x
      let printTable = document.getElementById(id)
      let length = this.styleNumberList.length

      for (index; index < length; index++) {
        const e = this.styleNumberList[index]
        // console.log(index)
        // console.log(index+1)
        this.printTotal += Number(e.total)
        this.printMoney += Number(e.money)
        this.printSellingPrice += Number(e.sellingPriceMoney)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index + 1
        row.insertCell(1).innerHTML = e.styleNumber + '-' + e.colorNo
        row.insertCell(2).innerHTML = e.colorName
        row.insertCell(3).innerHTML = e.commodityName
        row.insertCell(4).innerHTML = e.c05
        row.insertCell(5).innerHTML = e.c07
        row.insertCell(6).innerHTML = e.c09
        row.insertCell(7).innerHTML = e.c11
        row.insertCell(8).innerHTML = e.c13
        row.insertCell(9).innerHTML = e.c15
        row.insertCell(10).innerHTML = e.c17
        row.insertCell(11).innerHTML = e.c19
        row.insertCell(12).innerHTML = e.c21
        row.insertCell(13).innerHTML = e.c23
        row.insertCell(14).innerHTML = e.f
        row.insertCell(15).innerHTML = e.total
        row.insertCell(16).innerHTML = e.onePrice
        row.insertCell(17).innerHTML = e.money

        if (
          parseInt((index + 1) / 33) &&
          (index + 1) % 33 == 0 &&
          index + 1 != length
        ) {
          // console.log('33倍数')
          let pageIndex = index + 3 - parseInt(index / 33) * 33
          // console.log(pageIndex)
          // console.log(index+1)    // 33
          // console.log(length)     // 36
          let startingPoint = index - 32
          let pageTotal = 0
          let pageMoney = 0
          for (let j = startingPoint; j <= index; j++) {
            pageTotal += this.styleNumberList[j].total
            pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
          }

          let rowEnd = printTable.insertRow(printTable.FetchRowCount)
          rowEnd.insertCell(0).innerHTML = '本页小计：'
          printTable.rows[pageIndex].cells[0].colSpan = '2'
          rowEnd.insertCell(1).innerHTML = pageTotal
          printTable.rows[pageIndex].cells[1].colSpan = '2'
          rowEnd.insertCell(2).innerHTML = '汇总金额：'
          printTable.rows[pageIndex].cells[2].colSpan = '4'
          rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
          printTable.rows[pageIndex].cells[3].colSpan = '10'

          let newHead = document.createElement('div')
          newHead.classList.add('addPrintHead')
          newHead.innerHTML = `
            <p class="rightTag" style="top: ${
              ((index + 1) / 33) * 29.7 + 3
            }cm;">白联仓库 红联财务 黄联客户</p>
            <span class="printHead">
              ${this.companyName}${this.jxQuarter}客户销货单
            </span>
            <div class="info" style="height: 25px;">
              <p style="margin: 5px 0;">客户：${this.printVendorName}</p>
              <p style="margin: 5px 0;">联系人：${this.contact}</p>
              <p style="margin: 5px 0;">销货序号：${this.sequence}</p>
            </div>
            <div class="info" style="height: 25px;">
              <p style="margin: 5px 0;">客户电话：${this.phone}</p>
              <p style="margin: 5px 0;">出货类型：${this.cooperateWay}</p>
              <p style="margin: 5px 0;">销货日期：${this.printDate}</p>
            </div>
          `
          newHead.style.pageBreakBefore = 'always'
          this.insertAfter(newHead, printTable)

          let tableId = `printTable${(index + 1) / 33}`
          // console.log(tableId)
          let tableDom = document.createElement('table')
          tableDom.border = '1'
          tableDom.align = 'center'
          tableDom.id = tableId
          tableDom.innerHTML = `
            <thead>
              <tr>
                <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                <td rowspan="2" style="text-align: center;width: 5%;">单价</td>
                <td rowspan="2" style="text-align: center;">金额</td>
              </tr>
              <tr>
                <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                <td style="text-align: center;border-top: 1px dotted;">S</td>
                <td style="text-align: center;border-top: 1px dotted;">M</td>
                <td style="text-align: center;border-top: 1px dotted;">L</td>
                <td style="text-align: center;border-top: 1px dotted;">XL</td>
                <td style="text-align: center;border-top: 1px dotted;">2L</td>
                <td style="text-align: center;border-top: 1px dotted;">3L</td>
                <td style="text-align: center;border-top: 1px dotted;">4L</td>
                <td style="text-align: center;border-top: 1px dotted;">5L</td>
                <td style="text-align: center;border-top: 1px dotted;">6L</td>
                <td style="text-align: center;border-top: 1px dotted;"></td>
              </tr>
            </thead>
          `
          // console.log(tableDom)
          // console.log(index)
          this.printStyleCount(e.styleNumber)
          this.insertAfter(tableDom, newHead)
          this.openPrint(index + 2, tableId)
          return
        }
        if (index + 1 == length) {
          let pageIndex = index + 3 - parseInt(index / 33) * 33
          // console.log('最后一行')
          let startingPoint = index < 33 ? 0 : parseInt(index / 33) * 33
          let pageTotal = 0
          let pageMoney = 0
          for (let j = startingPoint; j <= index; j++) {
            pageTotal += this.styleNumberList[j].total
            pageMoney += Number(this.styleNumberList[j].sellingPriceMoney)
          }
          let rowEnd = printTable.insertRow(printTable.FetchRowCount)
          rowEnd.insertCell(0).innerHTML = '本页小计：'
          printTable.rows[pageIndex].cells[0].colSpan = '2'
          rowEnd.insertCell(1).innerHTML = pageTotal
          printTable.rows[pageIndex].cells[1].colSpan = '2'
          rowEnd.insertCell(2).innerHTML = '汇总金额：'
          printTable.rows[pageIndex].cells[2].colSpan = '4'
          rowEnd.insertCell(3).innerHTML = pageMoney.toFixed(2)
          printTable.rows[pageIndex].cells[3].colSpan = '10'
        }
        this.printStyleCount(e.styleNumber)
      }

      // console.log(this.styleList)
      this.printStyle = this.styleList.length
      let int = setInterval(() => {
        if (this.printStyle) {
          clearInterval(int)
          let printHtml = document.getElementById('p').innerHTML
          let wind = window.open(
            '',
            'newwindow',
            'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'
          )
          wind.document.body.innerHTML = printHtml
          let style = document.createElement('style')
          style.type = 'text/css'
          style.innerHTML = resources.printCSS
          wind.document.head.appendChild(style)
          wind.print()
          return false
        }
      }, 500)
    },
    clearPrintTable() {
      let printTable = document.getElementById('printTable')
      let trs = printTable.getElementsByTagName('tr')
      let len = trs.length - 1
      for (let i = len; i > 1; i--) {
        printTable.deleteRow(i)
      }

      let printArea = document.getElementById('p')
      let tables = printArea.getElementsByTagName('table')
      len = tables.length
      for (let i = 1; i < len; i++) {
        tables[1].remove()
      }
      let addPrintHeads = document.getElementsByClassName('addPrintHead')
      len = addPrintHeads.length
      for (let i = 0; i < len; i++) {
        addPrintHeads[0].remove()
      }
    },
    printStyleCount(s) {
      if (!this.styleList.length) {
        this.styleList.push(s)
      } else {
        let exist = 0
        for (const i of this.styleList) {
          // console.log(i)
          if (i == s) {
            exist = 1
            break
          }
        }
        if (!exist) {
          this.styleList.push(s)
        }
      }
    },
    // insertAfter(p,header1) // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法
    insertAfter(newElement, targetElement) {
      // newElement是要追加的元素 targetElement 是指定元素的位置
      let parent = targetElement.parentNode // 找到指定元素的父节点
      if (parent.lastChild == targetElement) {
        // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
        parent.appendChild(newElement, targetElement)
      } else {
        parent.insertBefore(newElement, targetElement.nextSibling)
      }
    },

    // 客户编号失去焦点
    customerNoBlur() {
      if (this.customerNo) {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },
    // 导入
    async handleImportInputClick(evt) {
      const params = {
        no: '客户编号',
        warehouseNo: '仓库编号',
        kindsNumber: '货号',
        number: '数量'
      }
      const dataList = await importExcel(evt, params)
      const { data } = await importCustomerSell(dataList)
      if (data && data.code === 200 && data.data) {
        this.$message.success(data.msg)
        this.switchList = data.data.validList || []
      }
    },
    // readExcel(e) {
    //   if (!this.inputDate) {
    //     this.$alert('日期不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }
    //   if (!this.customerNo) {
    //     this.$alert('客户不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }
    //   if (!this.discount) {
    //     this.$alert('折数不能为空', '', {
    //       confirmButtonText: '确定'
    //     })
    //     return
    //   }

    //   const files = e.target.files
    //   if (files.length <= 0) {
    //     //如果没有文件名
    //     return false
    //   } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    //     this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
    //     return false
    //   }

    //   this.tmpKindsNumberList = []
    //   let that = this
    //   let lastKN = []

    //   if (this.kindsNumberList.length) {
    //     this.kindsNumberList.forEach((e) => {
    //       // console.log(e)
    //       lastKN.push(e.kindsNumber)
    //     })
    //   }
    //   const fileReader = new FileReader()
    //   fileReader.onload = (ev) => {
    //     try {
    //       const data = ev.target.result
    //       const workbook = XLSX.read(data, {
    //         type: 'binary'
    //       })
    //       const wsname = workbook.SheetNames[0] //取第一张表
    //       const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
    //       console.log(ws)
    //       // return

    //       let kindsNumberNumMap = {}
    //       ws.forEach((e) => {
    //         kindsNumberNumMap[e.货号] = e.数量
    //       })
    //       // 是否有信息变动
    //       let isNew = false

    //       if (JSON.stringify(this.originalData) == '{}') {
    //         // 第一次点读卡，记录原始数据
    //         this.originalData.inputDate = this.inputDate
    //         this.originalData.customerNo = this.customerNo
    //         this.originalData.inputSequence = this.inputSequence
    //         this.originalData.discount = this.discount
    //         this.originalData.cooperateWay = this.cooperateWay
    //         this.originalData.onePrice = this.onePrice
    //         this.originalData.remark = this.remark
    //       } else {
    //         // 判断是否修改了数据
    //         for (const key in this.originalData) {
    //           if (this.originalData.hasOwnProperty(key)) {
    //             const e = this.originalData[key]
    //             if (e != this[key]) {
    //               // 修改了数据 重新赋值
    //               isNew = true
    //               this.originalData.inputDate = this.inputDate
    //               this.originalData.inputSequence = this.inputSequence
    //               this.originalData.customerNo = this.customerNo
    //               this.originalData.discount = this.discount
    //               this.originalData.cooperateWay = this.cooperateWay
    //               this.originalData.onePrice = this.onePrice
    //               this.originalData.remark = this.remark
    //               break
    //             }
    //           }
    //         }
    //       }

    //       if (this.sequence != '' && !isNew) {
    //         // 有序号并且信息没改，再点读卡，传右表
    //         // console.log('没有数据变动')
    //       } else {
    //         // console.log('第一次或有数据变动')
    //         // 有数据变动，进厂序号改空
    //         // console.log(this.sequence)
    //         this.sequence = ''
    //         this.switchList = []
    //         this.kindsNumberList = []
    //         this.styleNumberList = []
    //       }

    //       let d = {
    //         // 是否打开条码扫描（0没打开：输入款号色号 1已打开：货号）
    //         isScan: 0,
    //         // 是否是补单（补货数据（0否 1是））
    //         isReplenishment: this.sequence ? 1 : 0,
    //         // 是否返现（0不返现 1返现）
    //         // isReturn: this.checked2 ? 1 : 0,
    //         // 返现金额=实收单价
    //         // realMoney: this.onePrice,
    //         sellDate: this.inputDate,
    //         customerNo: this.customerNo,
    //         inputSequence: this.inputSequence,
    //         sequence: this.sequence,
    //         // warehouseNo: this.warehouseNo,
    //         discount: this.discount,
    //         cooperateWay: this.cooperateWay,
    //         remark: this.remark,
    //         // 扫描数量
    //         scanNum: e.数量,
    //         // 货号（条码扫描打开所传值）
    //         scanKindsNumber: e.货号,
    //         kindsNumberNumMap
    //       }
    //       console.log(d)
    //       sellByKindsNumberContinue(JSON.stringify(d)).then((res) => {
    //         console.log(res)
    //         this.$refs.upload.value = ''
    //         if (res.data.code == 200) {
    //           if (res.data.data.validList && res.data.data.validList.length) {
    //             this.sequence = res.data.data.validList[0].sequence
    //             this.twoDimensional = false
    //             this.getData()
    //           }
    //         }
    //       })
    //     } catch (error) {
    //       console.log(error)
    //       return
    //     }
    //   }
    //   fileReader.readAsBinaryString(files[0])
    // },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map((item) => Number(item[prop]))
        if (!values.every((value) => isNaN(value))) {
          if (
            prop == 'c05' ||
            prop == 'c07' ||
            prop == 'c09' ||
            prop == 'c11' ||
            prop == 'c13' ||
            prop == 'c15' ||
            prop == 'c17' ||
            prop == 'c19' ||
            prop == 'c21' ||
            prop == 'c23' ||
            prop == 'f' ||
            prop == 'total' ||
            prop == 'sum' ||
            prop == 'sellingPriceMoney' ||
            prop == 'money'
          ) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            if (!sums[index]) {
              sums[index] = ''
            }
            let decimal = sums[index].toString().split('.')[1]
            if (decimal && decimal.length > 2) {
              sums[index] = sums[index].toFixed(2)
            }
          }
        }
      })
      return sums
    },

    newNo() {
      if (this.$route.query.oid || this.readOnly) return
      this.sequence = ''
      this.switchList = []
      this.kindsNumberList = []
      this.styleNumberList = []
      this.isConfirm = false
    },

    getData() {
      getSellInquire({
        sellSequence: this.sequence,
        limit: 99999,
        page: 1
      }).then((res) => {
        this.total = 0
        this.kindsNumberList = res.data.data.sellInquireInfoList
        this.isConfirm = this.kindsNumberList[0].affirm

        this.kindsNumberList.sort((a, b) => {
          return a.kindsNumber.localeCompare(b.kindsNumber)
        })
        this.switchList = this.kindsNumberList
        this.kindsNumberList.forEach((e) => {
          this.total += Number(e.sum)
        })
      })
      getSellInquire({
        twoInfo: 1,
        sellSequence: this.sequence,
        limit: 9999,
        page: 1
      }).then((res) => {
        this.styleNumberList = res.data.data.customerSellInfoTwos
        this.styleNumberList.forEach((e) => {
          e.colorNoName = e.colorNo + '.' + e.colorName
          e.styleNumber = e.typeNumber
          e.total =
            Number(e.c05) +
            Number(e.c07) +
            Number(e.c09) +
            Number(e.c11) +
            Number(e.c13) +
            Number(e.c15) +
            Number(e.c17) +
            Number(e.c19) +
            Number(e.c21) +
            Number(e.c23) +
            Number(e.f)
          e.sellingPriceMoney = (e.total * e.sellingPrice).toFixed(2)

          if (e.c05 === 0) e.c05 = ''
          if (e.c07 === 0) e.c07 = ''
          if (e.c09 === 0) e.c09 = ''
          if (e.c11 === 0) e.c11 = ''
          if (e.c13 === 0) e.c13 = ''
          if (e.c15 === 0) e.c15 = ''
          if (e.c17 === 0) e.c17 = ''
          if (e.c19 === 0) e.c19 = ''
          if (e.c21 === 0) e.c21 = ''
          if (e.c23 === 0) e.c23 = ''
          if (e.f === 0) e.f = ''
        })
        this.readOnly = false
      })
    }
  }
}
</script>
